#!/usr/bin/env python3
"""
简单的测试服务器，用于调试file接口问题
"""

from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import cv2
import numpy as np
import base64
import logging

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="简单YOLO测试服务")

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/health")
async def health():
    """健康检查"""
    logger.info("收到健康检查请求")
    return {"status": "healthy", "message": "简单测试服务器运行正常"}

@app.post("/detect/file")
async def detect_file(file: UploadFile = File(...)):
    """简单的文件检测接口"""
    try:
        logger.info(f"收到文件检测请求: {file.filename}")
        
        # 读取文件
        contents = await file.read()
        logger.info(f"文件读取完成，大小: {len(contents)} bytes")
        
        # 解码图像
        nparr = np.frombuffer(contents, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            logger.error("图像解码失败")
            return {"success": False, "message": "图像解码失败"}
        
        logger.info(f"图像解码成功，尺寸: {image.shape}")
        
        # 模拟检测结果
        fake_results = [
            {
                "class_id": 0,
                "class_name": "person",
                "confidence": 0.85,
                "bbox": [100, 100, 200, 300],
                "area": 20000
            }
        ]
        
        # 绘制结果图像
        result_image = image.copy()
        cv2.rectangle(result_image, (100, 100), (200, 300), (0, 255, 0), 2)
        cv2.putText(result_image, "person 0.85", (100, 95), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        
        # 编码为base64
        _, buffer = cv2.imencode('.jpg', result_image)
        result_image_base64 = base64.b64encode(buffer).decode('utf-8')
        
        result = {
            "success": True,
            "message": "检测完成",
            "model_name": "test_model",
            "results": fake_results,
            "inference_time": 0.1,
            "preprocessing_time": 0.01,
            "postprocessing_time": 0.02,
            "total_time": 0.13,
            "image_size": [image.shape[1], image.shape[0]],
            "result_image": result_image_base64
        }
        
        logger.info(f"准备返回结果，检测到 {len(fake_results)} 个对象")
        return result
        
    except Exception as e:
        logger.error(f"检测失败: {e}")
        return {
            "success": False,
            "message": f"检测失败: {str(e)}",
            "results": []
        }

if __name__ == "__main__":
    logger.info("启动简单测试服务器...")
    uvicorn.run(app, host="0.0.0.0", port=8001, log_level="info")
